package com.xinnet.mms.customtransfer.service.impl;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.xinnet.core.utils.ConfigUtil;
import com.xinnet.core.utils.page.PageView;
import com.xinnet.mms.allot.service.CustomAllotService;
import com.xinnet.mms.common.AppGlobalContainer;
import com.xinnet.mms.customerManage.dao.CustomerManageDao;
import com.xinnet.mms.customerstate.dao.CustomerStateHistDao;
import com.xinnet.mms.customtransfer.service.NewRegisterCustomTransferService;
import com.xinnet.mms.empcustomrelation.dao.EmpCustomRelationDao;
import com.xinnet.mms.entity.CustomStateHist;
import com.xinnet.mms.entity.Customer;
import com.xinnet.mms.entity.EmpCustomRelation;
import com.xinnet.mms.entity.Product;
import com.xinnet.mms.entity.PublicConfig;
import com.xinnet.mms.utils.CustomerManage;

@Service("newRegisterCustomTransferService")
public class NewRegisterCustomTransferServiceImpl implements NewRegisterCustomTransferService{
	@Autowired
	private EmpCustomRelationDao empCustomRelationDao;
	@Autowired
	private CustomerStateHistDao customerStateHistDao;
	@Autowired
	private CustomerManageDao customerManageDao;
	@Autowired
	private CustomAllotService customAllotService;
	
	private static Logger log=LoggerFactory.getLogger(NewRegisterCustomTransferServiceImpl.class);
	/**j
	 * 新注册客户流转
	 */
	public void newRegisterCustomTransfer() throws Exception{
		//获取产品规则
		Map<String,Product> productRuleMap = AppGlobalContainer.productRuleMap;
		if(productRuleMap==null || productRuleMap.isEmpty()){
			log.info("没有可用的流转规则");
			return;
		}
		/*Map<Integer,List<EmpCustomRelation>> customerMap = (Map<Integer,List<EmpCustomRelation>>)AppGlobalContainer.transferCustomMap;
		if(customerMap==null || customerMap.isEmpty()){
			log.info("客户为空");
			return;
		}	
		//获取新注册客户
		List<EmpCustomRelation> newRegisterCustomList = customerMap.get(CustomerManage.NEW_CUSTOMER);
		if(newRegisterCustomList==null || newRegisterCustomList.isEmpty()){
			log.info("新注册客户为空");
			return;
		}*/
		
        String isTest = ConfigUtil.getString("isTest");
        if(isTest==null || "".equals(isTest)){
        	log.error("配置异常：是否是测试环境");
        	return;
        }
        log.info("************************************************************************************新注册客户流转开始********************************************"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
		//新注册客户流转
        //分页获取新注册客户信息
        Customer customer = new Customer();
        customer.setCustomType(CustomerManage.NEW_CUSTOMER);
        int count = empCustomRelationDao.getTransferCustomCount(customer);
        
        PageView<Customer> page = new PageView<Customer>();
        page.setPageSize(50000); //每页显示5w条
        page.setRowCount(count);
        
        long pageCount = page.getPageCount();
        
        for(int i = 1;i<=pageCount;i++){
        	page.setPageNow(i);
        	Integer startPage = page.getFirstResult();
    		customer.setLimitTop(startPage);
    		customer.setLimitDown(page.getPageSize());
        	
        	List<EmpCustomRelation> newRegisterCustomList = empCustomRelationDao.getTransferCustom(customer);
        	for (Iterator<EmpCustomRelation> iterator = newRegisterCustomList.iterator(); iterator.hasNext();) {
    			EmpCustomRelation newRegisterCustom = (EmpCustomRelation) iterator.next();
    			this.customTransferForNewRegisterCustomer(newRegisterCustom,isTest);
    		}
        }
       
		log.info("************************************************************************************新注册客户流转结束********************************************"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));

	}
	
	
	/**
	 * 对每个新注册客户流转
	 * @param newRegisterCustom
	 * @param isTest
	 * @param transferRuleList
	 * @throws Exception
	 */
	@Transactional(propagation=Propagation.REQUIRES_NEW,readOnly=false,rollbackFor=Exception.class)
	public void customTransferForNewRegisterCustomer(EmpCustomRelation newRegisterCustom,String isTest){
		String customId = newRegisterCustom.getCustomId();
		try {
			Customer tempCustomer = customAllotService.getCustomerById(newRegisterCustom.getCustomId());
			int customType = newRegisterCustom.getCustomType();
			String productId = tempCustomer.getProductId();
			if(productId==null || "".equals(productId)){
				productId = customAllotService.getDefaultProduct().getId();
			}
			tempCustomer.setDeptId(newRegisterCustom.getDeptno());
			java.util.Date createTime = newRegisterCustom.getCreateTime();
			//获取当前产品规则
			Product currentProductRule=AppGlobalContainer.productRuleMap.get(productId);
			if(currentProductRule==null){
				log.error("当前产品规则为空!"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())+"productId="+productId);
				return;
			}
			//计算超时时间
			Integer holdtime = currentProductRule.getSysallocationNodealholdtime();
			if(holdtime==null){
				log.error("当前产品holdtime为空!"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())+"productId="+productId);
				return;
			}
			Calendar calendar=Calendar.getInstance();
			calendar.setTime(createTime);
			if("true".equals(isTest)){
				calendar.add(Calendar.MINUTE, holdtime);
			}else if("false".equals(isTest)){
				calendar.add(Calendar.DATE, holdtime);
			}else{
				log.error("配置异常：是否是测试环境");
				return;
			}
			Date saleHoldTime=calendar.getTime();
			Date nowDate= new Date();
			if(nowDate.after(saleHoldTime)){
				/*Map<String,List<CustomStateHist>> customStateHistMap = AppGlobalContainer.customStateHistMap;
				List<CustomStateHist> customStateHistList = customStateHistMap.get(customId);
				Product pushProduct = AppGlobalContainer.getPushProduct(currentProductRule,customStateHistList);*/
				/*Map<String,List<EmpCustomRelation>> empCustomRelationMap = AppGlobalContainer.empCustomRelationMap;*/
				/*List<EmpCustomRelation> empCustomRelationList = empCustomRelationMap.get(customId);*/
				//获取可用的业绩保留期
				/*Map<String,PublicConfig> scoreHoldDateMap = AppGlobalContainer.scoreHoldDateMap;*/
				/*PublicConfig  publicConfig = scoreHoldDateMap.get("scoreHoldTime");*/
				if(customType==CustomerManage.NEW_CUSTOMER){
					
					/*if(pushProduct==null){
						boolean isCanGoOpenSea = this.isCanGoOpenSeaByScoreHoldTime(publicConfig,customId);
						if((empCustomRelationList==null || empCustomRelationList.size()<=1) && isCanGoOpenSea){
							//新注册客户超时已经没有可推送的产品线
							//查询最后接收人是否是当前人, 如果是进公海 删除员工关系;如果不是删除 员工关系 .
							empCustomRelationDao.getEmpCustomRelationByCustomId(customId);
							Customer newRegisterCustomer = new Customer();
							newRegisterCustomer.setCusId(customId);
							newRegisterCustomer.setCustomerType(CustomerManage.OPEN_SEA_CUSTOMER);
							customerManageDao.updateCustomType(newRegisterCustomer);
							newRegisterCustomer.setPushHistId(pushHistId);
							customAllotService.allot(newRegisterCustomer,CustomerManage.OPEN_SEA_CUSTOMER);
							log.info("新注册客户没有可推送产品进入公海：customer id"+customId+"  "+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
						}
						empCustomRelationDao.delEmpCustomRelationByCustomIdAndEmpNo(customId,empNo,productCode);
						customerStateHistDao.updateCustomStateHistByPushHistId(pushHistId);
					}else{
						
						//删除员工客户对应关系
						empCustomRelationDao.delEmpCustomRelationByCustomIdAndEmpNo(customId,empNo,productCode);
						customerStateHistDao.updateCustomStateHistByPushHistId(pushHistId);
						
						//客户流转
						Customer newRegisterCustomer = new Customer();
						String pushProductName= pushProduct.getProductName();
						String pushProductId = pushProduct.getId();
						String pushProductCode = pushProduct.getProductCode();
						newRegisterCustomer.setProductLabel(pushProductId);
						newRegisterCustomer.setProductName(pushProductName);
						newRegisterCustomer.setCusId(customId);
						newRegisterCustomer.setRegionalId(regionalId);
						newRegisterCustomer.setCompanyId(companyId);
						newRegisterCustomer.setProductLabel(pushProductCode);
						newRegisterCustomer.setCustomerType(CustomerManage.TWICE_NEW_CUSTOMER);
					   customerManageDao.updateCustomType(newRegisterCustomer);
					   newRegisterCustomer.setPushHistId(pushHistId);
					   customAllotService.allot(newRegisterCustomer,CustomerManage.TWICE_NEW_CUSTOMER);
					   log.info("新注册客户流转成二次开发新客户：customer id"+customId+"  "+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));*/
						//查询最后接收人是否是当前人, 如果是进公海 删除员工关系;如果不是删除 员工关系 .
						//boolean isCanGoOpenSea = this.isCanGoOpenSeaByScoreHoldTime(publicConfig,customId);
						//if((empCustomRelationList==null || empCustomRelationList.size()<=1) && isCanGoOpenSea){
							//新注册客户超时已经没有可推送的产品线
						//empCustomRelationDao.getEmpCustomRelationByCustomId(customId);
						tempCustomer.setCustomerType(CustomerManage.OPEN_SEA_CUSTOMER);
						customerManageDao.updateCustomType(tempCustomer);
						empCustomRelationDao.delEmpCustomRelationByCusId(tempCustomer.getCusId());
						customAllotService.allot(tempCustomer,CustomerManage.OPEN_SEA_CUSTOMER);
						//}
						/*empCustomRelationDao.delEmpCustomRelationByCustomIdAndEmpNo(customId,empNo,productCode);
						customerStateHistDao.updateCustomStateHistByPushHistId(pushHistId);*/
					}
					
				}else {
					//log.info("新注册客户未到期不进行流转id："+newRegisterCustom.getCustomId()+",nowdate:"+nowDate+",scoreHoldTime"+saleHoldTime);
				}
			
		} catch (Exception e) {
			log.error("新注册客户流转异常：customer id"+customId+"  "+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()),e);
		}
	}
	
	/**
	 * 根据业绩保留期 客户是否可以进入公海
	 * @param publicConfig
	 * @param createTime
	 * @return
	 */
	private boolean isCanGoOpenSeaByScoreHoldTime(PublicConfig publicConfig,String customId){
		if(publicConfig==null){
			return true;
		}
		String scoreHoldTime = publicConfig.getConfigValue();
		if(scoreHoldTime==null || "".equals(scoreHoldTime)){
			return true;
		}
		boolean isCanGoOpenSea = customerStateHistDao.isCanGoOpenSeaByScoreHoldTime(customId,scoreHoldTime);
		return isCanGoOpenSea;
	}
				
}
